<template>
	<view>
		<!-- 切换考试科目 start-->
		<!-- 考试科目选择头部 -->
		<view class="subject-header" @tap="goTo('/pages/index/profession/select')">
				<text class="subject-name">{{ currentExam.name}}</text>
				<text class="switch-icon cuIcon-right"></text>
			</view>
		
		<!-- 科目标签页 -->
		<view class="subject-tabs-wrapper">
			<scroll-view class="subject-tabs-scroll" scroll-x="true" show-scrollbar="false">
				<view class="subject-tabs-container">
					<view 
						v-for="(subject, index) in subjectList" 
						:key="index"
						:class="['subject-tab', activeTabIndex === index ? 'active' : '']"
						@tap="switchSubject(index)"
					>
						<text>{{ subject.name }}</text>
					</view>
				</view>
			</scroll-view>
			<!-- 筛选图标 -->
		<view class="filter-icon-container" @tap="goTo('/pages/index/profession/filter?exam_id=' + currentExam.id)">
			<text class="cuIcon-filter text-orange filter-icon"></text>
		</view>
		</view>

		<!-- 轮播图 -->
		<view class="swiper-container bg-white margin-top-xs radius shadow-warp">
			<swiper class="swiper" indicator-dots autoplay circular :interval="3000" :duration="500">
				<swiper-item v-for="(item, index) in swiperList" :key="index" @tap="handleSwiperClick(item)">
					<image class="swiper-image" :src="item.img_url" mode="aspectFill"></image>
				</swiper-item>
			</swiper>
		</view>
		
		<!-- 科目统计页 -->
		<view class="statistics-container bg-white margin-top-xs radius shadow-warp">
			<view class="statistics-content">
				<view class="statistics-item">
					<text class="statistics-number">{{ courseStats.today_question_count || 0 }}</text>
					<text class="statistics-label">今日答题</text>
				</view>
				<view class="statistics-divider"></view>
				<view class="statistics-item">
					<text class="statistics-number">{{ courseStats.total_question_count || 0 }}</text>
					<text class="statistics-label">总答题数</text>
				</view>
				<view class="statistics-divider"></view>
				<view class="statistics-item">
					<text class="statistics-number">{{ courseStats.correct_rate || 0 }}%</text>
					<text class="statistics-label">正确率</text>
				</view>
			</view>
		</view>
		<!-- 切换考试科目 end-->


		<!-- 题库分类 start-->
		<view class="question-category-container bg-white margin-top-xs radius shadow-warp">
			<view class="category-grid">
				<!-- 固定分类 - 前三个 -->
				<view class="category-grid-item" @tap="goToCourseDetail">
					<image class="category-icon" src="//file.20230611.cn/app_img/week.png" mode="aspectFit" style="width: 64rpx; height: 64rpx;"></image>
					<text class="category-name" style="font-size: 28rpx; font-weight: 500;">题库详情</text>
				</view>
				<view class="category-grid-item" @tap="goToDailyPractice">
					<image class="category-icon" src="//file.20230611.cn/app_img/icon_1.png" mode="aspectFit" style="width: 64rpx; height: 64rpx;"></image>
					<text class="category-name" style="font-size: 28rpx; font-weight: 500;">每日一练</text>
				</view>
				<view class="category-grid-item" @tap="goToSequentialPractice">
					<image class="category-icon" src="//file.20230611.cn/app_img/icon_8.png" mode="aspectFit" style="width: 64rpx; height: 64rpx;"></image>
					<text class="category-name" style="font-size: 28rpx; font-weight: 500;">顺序刷题</text>
				</view>
				<view class="category-grid-item" @tap="goToQuestionTypePractice">
					<image class="category-icon" src="//file.20230611.cn/app_img/icon_3.png" mode="aspectFit" style="width: 64rpx; height: 64rpx;"></image>
					<text class="category-name" style="font-size: 28rpx; font-weight: 500;">题型刷题</text>
				</view>
				
				<!-- 动态分类 - 章节练习和历年真题 -->
				<view class="category-grid-item" v-for="(category, index) in courseCategories" :key="index" @tap="handleCategoryClick(category)">
					<image class="category-icon" :src="category.image" mode="aspectFit" style="width: 64rpx; height: 64rpx;"></image>
					<text class="category-name" style="font-size: 28rpx; font-weight: 500;">{{ category.name }}</text>
				</view>
				
				<!-- 固定分类 - 后两个 -->
				<view class="category-grid-item" @tap="goToFavoritesPage">
					<image class="category-icon" src="//file.20230611.cn/app_img/icon_11.png" mode="aspectFit" style="width: 64rpx; height: 64rpx;"></image>
					<text class="category-name" style="font-size: 28rpx; font-weight: 500;">我的收藏</text>
				</view>
				<view class="category-grid-item" @tap="goToErrorPage">
					<image class="category-icon" src="//file.20230611.cn/app_img/icon_12.png" mode="aspectFit" style="width: 64rpx; height: 64rpx;"></image>
					<text class="category-name" style="font-size: 28rpx; font-weight: 500;">我的错题</text>
				</view>
			</view>
		</view>
		<!-- 题库分类 end-->

		<!-- 最新资讯组件 -->
		<index-article-list v-if="!appIsAudit" />

	</view>
</template>

<script>
import { post, get } from '@/common/js/http.js';
import { navigateByLinkType } from '@/common/js/util.js';
import IndexArticleList from './index-article-list.vue';

export default {
	components: {
		IndexArticleList
	},
	name: 'Index1',
	props: {
		// 移除不再需要的统计数据 props，现在从内部获取
	},
	data() {
		const app = getApp();
		const appIsAudit = app.globalData.appIsAudit;
		return {
			appIsAudit: appIsAudit,
			subjectList: [], // 课程列表
			currentExam: { name: '', id: '' },
			activeTabIndex: 0, // 添加内部数据管理
			courseCategories: [], // 添加课程分类内部数据
			courseStats: {}, // 添加课程统计信息
			swiperList: [], // 轮播图数据
		};
	},
	created() {
		// 组件创建时从缓存读取数据
		this.loadSubjectList();
		this.loadCurrentExam();
		this.loadCourseCategories(); // 添加课程分类数据加载
		this.loadSwiperData(); // 加载轮播图数据
	},

	methods: {
		loadSubjectList() {
			// 从缓存中读取课程数据
			let cachedCourseData = uni.getStorageSync('CACHE_COURSE');
			console.log('从缓存中读取课程数据:', cachedCourseData);
			if (cachedCourseData && Array.isArray(cachedCourseData)) {
				this.subjectList = cachedCourseData;
				return;
			}
			// 跳转到选择课程页面
			uni.navigateTo({
				url: '/pages/index/profession/select'
			});
		},
		loadCurrentExam() {
			// 从缓存中读取当前考试数据
			let cachedExamData = uni.getStorageSync('CACHE_EXAM');
			if (cachedExamData && cachedExamData.id) {
				this.currentExam = cachedExamData;
			} else {
				this.currentExam = { name: '', id: '' };
			}
		},
		// 简化页面跳转方法
		goTo(url) {
			uni.navigateTo({
				url: url
			});
		},
		// 顺序刷题 - 参考detail.js的逻辑
		async goToSequentialPractice() {
			const currentCourse = this.subjectList[this.activeTabIndex];
			if (!currentCourse?.id) {
				return;
			}
			
			try {
				const countInfo = await get('question/getCount', {
					course_id: currentCourse.id
				});
				const countInfoData = countInfo.data;
				console.log('题目数量:', countInfoData.count);
				
				if (countInfoData.count <= 0) {
					uni.showToast({
						title: '题库未上传题目',
						icon: 'none'
					});
					return;
				}
				
				let url =
					'/pages/practice/practice?title=' +
					currentCourse.name +
					'&mainType=0' +
					'&id=' +
					currentCourse.id +
					'&max_page=' + countInfoData.max_page +
					'&question_count=' + countInfoData.count;
				
				uni.navigateTo({
					url: url
				});
			} catch (error) {
				console.error('获取题目数量失败:', error);
				uni.showToast({
					title: '获取题目数量失败',
					icon: 'none'
				});
			}
		},
		// 题型刷题 - 参考detail.js的onQuestionTypePractice逻辑
		async goToQuestionTypePractice() {
			const currentCourse = this.subjectList[this.activeTabIndex];
			if (!currentCourse?.id) {
				return;
			}
			
			try {
				const countInfo = await get('question/getCount', {
					course_id: currentCourse.id
				});
				const countInfoData = countInfo.data;
				
				if (countInfoData.count <= 0) {
					uni.showToast({
						title: '题库未上传题目',
						icon: 'none'
					});
					return;
				}
				
				let url = '/pages/practice/topic/topic?mainType=0&title=' +
					currentCourse.name + '&code=' + (currentCourse.code || '') + '&id=' +
					currentCourse.id;
				
				uni.navigateTo({
					url: url
				});
			} catch (error) {
				console.error('获取题目数量失败:', error);
				uni.showToast({
					title: '获取题目数量失败',
					icon: 'none'
				});
			}
		},
		// 每日一练 - 先调用接口再跳转
		async goToDailyPractice() {
			// 提取参数
			const currentCourse = this.subjectList[this.activeTabIndex];
			const courseId = currentCourse?.id || '';

			// 预加载数据
			const res = await post('question/dailyPractice', {
				course_id: courseId
			});

			// 跳转到练习页面，传递课程ID、标题和主类型参数
			uni.navigateTo({
				url: '/pages/practice/practice?id=' + courseId + '&title=每日一练&mainType=1&question_count=10'
			});
		},
		// 修改 switchSubject 方法，也直接在组件内部处理
		switchSubject(index) {
			this.activeTabIndex = index;
			// 切换科目后重新加载课程分类数据
			this.loadCourseCategories();
		},
		// 简化错误页面跳转
		goToErrorPage() {
			const currentCourse = this.subjectList[this.activeTabIndex];
			const courseId = currentCourse?.id || '';
			this.goTo(`/pages/practice/error/error?course_id=${courseId}`);
		},
		goToFavoritesPage() {
			const currentCourse = this.subjectList[this.activeTabIndex];
			if (currentCourse?.id) {
				uni.navigateTo({
					url: '/pages/practice/coll/coll?course_id=' + currentCourse.id
				});
			}
		},
		goToCourseDetail() {
			const currentCourse = this.subjectList[this.activeTabIndex];
			if (currentCourse?.id) {
				uni.navigateTo({
					url: '/pages/practice/course/detail?id=' + currentCourse.id
				});
			}
		},
		handleCategoryClick(category) {
			const currentCourse = this.subjectList[this.activeTabIndex];
			if (!currentCourse?.id) return;
			
			const url = category.is_multi_level
				? `/pages/practice/paper/category?title=${category.name}&category_id=${category.id}&course_id=${currentCourse.id}`
				: `/pages/practice/paper/paper?title=${category.name}&category_id=${category.id}`;
			
			uni.navigateTo({ url });
		},
		
		// 获取科目列表数据
		// 获取课程分类数据
		async loadCourseCategories() {
			const currentCourse = this.subjectList[this.activeTabIndex];
			if (!currentCourse?.id) {
				this.courseCategories = [];
				return;
			}
			
			try {
				// 使用真实的API接口获取课程分类
				const categoryRes = await post('paper/category/list', {
					course_id: currentCourse.id,
					level: 1
				});
				console.log('获取课程分类成功：', categoryRes.data);
				this.courseCategories = categoryRes.data || [];
				
				// 获取课程统计信息
				const statsParams = {
					course_id: currentCourse.id
				};
				
				const statsRes = await get('course/getUserStats', statsParams);
				if (statsRes && statsRes.data) {
					// 这里可以根据需要处理统计信息，例如存储到组件数据中
					console.log('获取课程统计信息成功：', statsRes.data);
					this.courseStats = statsRes.data || {};
				}
			} catch (error) {
				console.error('获取课程分类或统计信息失败:', error);
				this.courseCategories = [];
				this.courseStats = {};
			}
		},
		
		// 获取轮播图数据
		async loadSwiperData() {
			try {
				const swiperRes = await get('swiper/get');
				console.log('获取轮播图成功：', swiperRes.data);
				this.swiperList = swiperRes.data || [];
				console.log('轮播图数据：', this.swiperList);
			} catch (error) {
				console.error('获取轮播图失败:', error);
				this.swiperList = [];
			}
		},
		
		// 处理轮播图点击事件
		handleSwiperClick(item) {
			if (item.target_url) {
				// 使用封装的工具函数处理链接类型跳转
				navigateByLinkType(item.target_type, item.target_url);
			}
		}
	}
};
</script>

<style scoped>
@import './index1.css';
</style>